/**
 * Created by admin on 2018/1/26.
 */
layui.config({
    base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;

    //加载页面数据
    var roleData = '';
    $.ajax({
        url : "role/roleQuery",
        type : "get",
        dataType : "json",
        success : function(data){
            roleData = data;
            if(window.sessionStorage.getItem("addRole")){
                var addRole = window.sessionStorage.getItem("addRole");
                roleData = JSON.parse(addRole).concat(roleData);
            }
            //执行加载数据的方法
            roleList();
        }
    })
    $(".show_all").click(function(){
    		$.ajax({
    	        url : "role/roleQuery",
    	        type : "get",
    	        dataType : "json",
    	        success : function(data){
    	            roleData = data;
    	            if(window.sessionStorage.getItem("addRole")){
    	                var addRole = window.sessionStorage.getItem("addRole");
    	                roleData = JSON.parse(addRole).concat(roleData);
    	            }
    	            //执行加载数据的方法
    	            roleList();
    	        }
    	    })
            
   })
    //全文查询
    $(".search_btn").click(function(){
        var newArray = [];
        if($(".search_input").val() != ''){
        	var search_input = $(".search_input").val();
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "role/globalQuery?search_input="+search_input,
                    type : "get",
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addRole")){
                            var addRole = window.sessionStorage.getItem("addRole");
                            roleData = JSON.parse(addRole).concat(data);
                        }else{
                            roleData = data;
                        }
                        for(var i=0;i<roleData.length;i++){
                            var roleStr = roleData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //用户ID
                            if(roleStr.userId.indexOf(selectStr) > -1){
                                roleStr["userId"] = changeStr(roleStr.userId);
                            }
                            //用户名
                            if(roleStr.userName.indexOf(selectStr) > -1){
                                roleStr["userName"] = changeStr(roleStr.userName);
                            }
                            //用户权限
                            if(roleStr.role.indexOf(selectStr) > -1){
                                roleStr["role"] = changeStr(roleStr.role);
                            }
                            //最后登录时间
                            if(roleStr.lastTime != null && roleStr.lastTime != ""){
                            	if(roleStr.lastTime.indexOf(selectStr) > -1){
                                    roleStr["lastTime"] = changeStr(roleStr.lastTime);
                                }
                            }
                            if(roleStr.userId.indexOf(selectStr)>-1 || roleStr.userName.indexOf(selectStr)>-1 || roleStr.role.indexOf(selectStr)>-1||roleStr.lastTime.indexOf(selectStr)>-1){
                                newArray.push(roleStr);
                            }
                        }
                        roleData = newArray;
                        roleList(roleData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })

    //添加损失信息
    $(".roleAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加用户",
            type : 2,
            content : "roleAdd",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })

    //批量删除
    $(".batchDel").click(function(){
        var $checkbox = $('.role_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.role_list tbody input[type="checkbox"][name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                setTimeout(function(){
                    //删除数据
                    for(var j=0;j<$checked.length;j++){
                        for(var i=0;i<roleData.length;i++){
                            if(roleData[i].userId == $checked.eq(j).parents("tr").find(".role_del").attr("data-id")){
                            	
                                roleData.splice(i,1);
                                roleList(roleData);
                            }
                        }
                    }
                    $('.role_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                    layer.close(index);
                    layer.msg("删除成功");
                },2000);
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断信息是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        data.elem.checked;
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })
    //高级查询
    $(".advanced_search").click(function(){
        var newArray = [];
        if($(".userId").val() != '' || $(".userName").val() != '' || $(".roleLevel").val() != ''
        	|| $(".lastTime").val() != ''){
        	var params = {};
        	params.userId = $(".userId").val();
        	params.userName = $(".userName").val();
        	params.role = $(".role").val();
        	params.lastTime = $(".lastTime").val();
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "role/advancedQuery",
                    data : params,
                    type : "get",
                    dataType : "json",
                    success : function(data){
                    	if(window.sessionStorage.getItem("addRole")){
                            var addRole = window.sessionStorage.getItem("addRole");
                            roleData = JSON.parse(addRole).concat(data);
                        }else{
                            roleData = data;
                        }
                        for(var i=0;i<roleData.length;i++){
                            var roleStr = roleData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //用户ID
//                            if(roleStr.userId.indexOf(selectStr) > -1){
//                                roleStr["userId"] = changeStr(roleStr.userId);
//                            }
//                            //用户名
//                            if(roleStr.userName.indexOf(selectStr) > -1){
//                                roleStr["userName"] = changeStr(roleStr.userName);
//                            }
//                            //用户权限
//                            if(roleStr.role.indexOf(selectStr) > -1){
//                                roleStr["role"] = changeStr(roleStr.role);
//                            }
//                            //最后登录时间
//                            if(roleStr.lastTime != null && roleStr.lastTime != ""){
//                            	if(roleStr.lastTime.indexOf(selectStr) > -1){
//                                    roleStr["lastTime"] = changeStr(roleStr.lastTime);
//                                }
//                            }
                            if(roleStr.userId.indexOf(selectStr)>-1 || roleStr.userName.indexOf(selectStr)>-1 || roleStr.role.indexOf(selectStr)>-1||roleStr.lastTime.indexOf(selectStr)>-1){
                                newArray.push(roleStr);
                            }
                        }
                        roleData = newArray;
                        roleList(roleData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })
    //操作
    $("body").on("click",".role_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<roleData.length;i++){
                if(roleData[i].userId == _this.attr("data-id")){
                	$.ajax({
                		url : "role/delete?userId="+roleData[i].userId,
                		type : "post"
                	})
                    roleData.splice(i,1);
                    roleList(roleData);
                }
            }
            layer.close(index);
        });
    })

    function roleList(that){
        //渲染数据
        function renderDate(data,curr){
            var dataHtml = '';
            if(!that){
                currData = roleData.concat().splice(curr*nums-nums, nums);
            }else{
                currData = that.concat().splice(curr*nums-nums, nums);
            }
            if(currData.length != 0){
                for(var i=0;i<currData.length;i++){
                    dataHtml += '<tr>'
                        +'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                        +'<td>'+currData[i].userId+'</td>'
                        +'<td>'+currData[i].userName+'</td>'
                        +'<td>'+currData[i].role+'</td>'
                        +'<td>'+currData[i].lastTime+'</td>'
                        +'<td>'
                        +  '<a class="layui-btn layui-btn-mini role_edit" href="roleSurveryRevise?userId='+currData[i].userId+'"><i class="iconfont icon-edit"></i> 编辑</a>'
                        +  '<a class="layui-btn layui-btn-danger layui-btn-mini role_del" data-id="'+data[i].userId+'" ><i class="layui-icon">&#xe640;</i> 删除</a>'
                        +'</td>'
                        +'</tr>';
                }
            }else{
                dataHtml = '<tr><td colspan="6" style="text-align: center">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 5; //每页出现的数据量
        if(that){
            roleData = that;
        }
        laypage({
            cont : "page",
            skip:true,
            pages : Math.ceil(roleData.length/nums),
            jump : function(obj,first){
                $(".role_content").html(renderDate(roleData,obj.curr));
                $('.role_list thead input[type="checkbox"]').prop("checked",false);
                form.render();
                if(!first){
                    layer.msg('第'+obj.curr+'页');
                }
            }
        })
    }
})